#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Ford UK NGc2 爬虫模型数据抓取模块 - API简化版
移除了所有UI抓取、点击、滚动等复杂逻辑
直接使用Ford API获取所有车型信息
"""

import time
import json
import requests
from selenium.webdriver.common.by import By
from .car_series import CarSeries
from .car_object import CarObject
from .car_extras import CarExtras


class ModelScraper:
    """模型数据抓取器 - API简化版"""
    
    def __init__(self, driver, wait, page_utilities):
        """
        初始化模型抓取器
        
        Args:
            driver: WebDriver实例 (用于获取session cookies)
            wait: WebDriverWait实例 (保留兼容性)
            page_utilities: 页面工具类实例
        """
        self.driver = driver
        self.wait = wait
        self.page_utilities = page_utilities
    
    def scrape_model_data(self, config):
        """
        抓取车型数据的主方法 - API版
        
        Args:
            config: 配置信息
            
        Returns:
            CarSeries: 车系对象
        """
        print("📋 开始抓取车型数据 (API简化版)...")
        print("✂️  已移除所有UI抓取逻辑，直接使用Ford API")
        
        try:
            # 解析URL参数
            url = config['sub_model']['url']
            catalog_id, series_code, default_paint = self.page_utilities.parse_url_parameters(url)
            
            # 提取车系名称（从URL中推断）
            model_name = self._extract_model_name_from_url(url)
            
            # 创建车系对象
            car_series = CarSeries(
                car_series_name=model_name,
                catalog_id=catalog_id,
                series_code=series_code,
                default_paint=default_paint
            )
            
            print(f"车系信息: {model_name}, 目录ID: {catalog_id}, 车系代码: {series_code}")
            
            # 直接从API获取所有车型数据（无需UI交互）
            all_models = self._fetch_all_models_from_api(config)
            
            if not all_models:
                print("❌ API调用失败，未获取到车型数据")
                return car_series
            
            print(f"✅ 从API获取到 {len(all_models)} 个车型")
            
            # 创建CarObject实例
            self._create_car_objects(car_series, all_models, model_name)
            
            return car_series
            
        except Exception as e:
            print(f"❌ 抓取车型数据失败: {e}")
            return CarSeries(
                car_series_name="Focus",
                catalog_id=catalog_id if 'catalog_id' in locals() else "",
                series_code=series_code if 'series_code' in locals() else "",
                default_paint=default_paint if 'default_paint' in locals() else ""
            )
    
    def _fetch_all_models_from_api(self, config):
        """从Ford API获取所有车型数据 - 无UI交互"""
        try:
            print("🌐 正在从Ford API获取车型数据...")
            
            # 从配置文件读取API信息
            if 'api_endpoints' not in config:
                print("❌ 配置文件中未找到api_endpoints")
                return []
            
            api_config = config['api_endpoints']
            if 'vehicle_model' not in api_config or 'load' not in api_config['vehicle_model']:
                print("❌ 配置文件中未找到vehicle_model.load API配置")
                return []
            
            load_config = api_config['vehicle_model']['load']
            base_url = load_config['url']
            base_params = load_config['params'].copy()
            series_codes = load_config.get('series_codes', {})
            key_features_path = load_config.get('key_features_path', 'data.keyFeatures.walkup.combined.features')
            
            all_models = []
            
            # 为每个车型调用API
            for model_name, series_code in series_codes.items():
                print(f"  📡 获取 {model_name} ({series_code}) 的数据...")
                
                try:
                    # 构建请求参数
                    params = base_params.copy()
                    params['config'] = params['config'].replace('{SERIES_CODE}', series_code)
                    
                    # 获取session cookies（只需要一次浏览器访问）
                    cookies = self._get_browser_cookies()
                    
                    # 发送API请求
                    response = requests.get(base_url, params=params, cookies=cookies, timeout=30)
                    
                    if response.status_code == 200:
                        data = response.json()
                        
                        # 提取Key Features
                        key_features = self._extract_key_features_from_response(data, key_features_path)
                        
                        # 提取价格信息
                        price = self._extract_price_from_response(data)
                        
                        model_data = {
                            'model_name': model_name,
                            'series_code': series_code,
                            'price': price,
                            'Key Features': key_features
                        }
                        
                        all_models.append(model_data)
                        print(f"    ✅ {model_name}: {len(key_features)} 个特性, 价格: {price}")
                        
                    else:
                        print(f"    ❌ {model_name}: API请求失败 (状态码: {response.status_code})")
                    
                    # 适当延迟，避免被限流
                    time.sleep(0.5)
                        
                except Exception as e:
                    print(f"    ❌ {model_name}: API调用异常: {e}")
                    continue
            
            return all_models
            
        except Exception as e:
            print(f"❌ 从API获取车型数据失败: {e}")
            return []
    
    def _get_browser_cookies(self):
        """从浏览器获取session cookies"""
        try:
            cookies = {}
            browser_cookies = self.driver.get_cookies()
            
            for cookie in browser_cookies:
                cookies[cookie['name']] = cookie['value']
            
            return cookies
            
        except Exception as e:
            print(f"⚠️ 获取browser cookies失败: {e}")
            return {}
    
    def _extract_key_features_from_response(self, data, key_features_path):
        """从API响应中提取Key Features - 修正版"""
        try:
            # 正确的路径是：data.keyFeatures.walkup.combined.features
            key_features_data = data.get('data', {}).get('keyFeatures', {}).get('walkup', {}).get('combined', {}).get('features', [])
            
            if not key_features_data:
                print(f"    ⚠️ 在路径 data.keyFeatures.walkup.combined.features 中未找到特性数据")
                return []
            
            features = []
            for feature in key_features_data:
                if isinstance(feature, dict):
                    # 提取descKf字段作为Key Feature描述
                    desc = feature.get('descKf', '')
                    if desc:
                        features.append(desc)
                    
                    # 如果没有descKf，尝试从packContent中提取
                    if not desc:
                        pack_content = feature.get('packContent', [])
                        for pack_item in pack_content:
                            if isinstance(pack_item, dict):
                                pack_desc = pack_item.get('descKf', '')
                                if pack_desc:
                                    features.append(pack_desc)
            
            print(f"    ✅ 成功提取 {len(features)} 个Key Features")
            return features
                
        except Exception as e:
            print(f"    ❌ 提取Key Features失败: {e}")
            return []
    
    def _extract_price_from_response(self, data):
        """从API响应中提取价格信息 - 修正版"""
        try:
            # 正确的路径是：data.price.basePrice.grossRetail
            price_data = data.get('data', {}).get('price', {})
            
            if not price_data:
                print("    ⚠️ 未找到价格数据")
                return "价格待查询"
            
            # 尝试多个价格字段
            base_price = price_data.get('basePrice', {})
            
            # 首选grossRetail（含税零售价）
            gross_retail = base_price.get('grossRetail')
            if gross_retail:
                return f"£{gross_retail:,.0f}"
            
            # 备选grossOTR（含税上路价）
            gross_otr = base_price.get('grossOTR') 
            if gross_otr:
                return f"£{gross_otr:,.0f}"
            
            # 备选netRetail（不含税零售价）
            net_retail = base_price.get('netRetail')
            if net_retail:
                return f"£{net_retail:,.0f} (不含税)"
            
            print("    ⚠️ 未找到有效的价格字段")
            return "价格待查询"
                
        except Exception as e:
            print(f"    ❌ 提取价格失败: {e}")
            return "价格待查询"
    
    def _extract_model_name_from_url(self, url):
        """从URL中提取车型名称"""
        try:
            # 从URL中提取Focus等车型名称
            if 'focus' in url.lower():
                return 'Focus'
            elif 'fiesta' in url.lower():
                return 'Fiesta'
            elif 'mustang' in url.lower():
                return 'Mustang'
            else:
                return 'Unknown'
        except:
            return 'Unknown'
    
    def _create_car_objects(self, car_series, all_models, model_name):
        """创建CarObject实例"""
        try:
            for model_data in all_models:
                model_name_str = model_data.get('model_name', 'Unknown')
                price = model_data.get('price', '价格待查询')
                key_features = model_data.get('Key Features', [])
                
                print(f"创建车款实体类: {model_name_str}")
                
                # 创建车款实体类
                car_object = CarObject(
                    series_name=model_name,  # 车系名
                    model_name=model_name_str,  # 车款名
                    price=price,
                    drive=""  # 可以从API获取更多信息
                )
                
                # 添加Key Features
                for feature in key_features:
                    if feature and feature.strip():  # 只添加非空的特性
                        car_object.add_key_feature(feature)
                
                # 添加一些默认的颜色（可以通过其他API获取真实颜色）
                car_object.add_color("red")
                car_object.add_color("blue")
                car_object.add_color("yellow")
                
                # 添加示例选装件（可以通过其他API获取真实选装件）
                extra1 = CarExtras("Blind Spot Information System", "$1234")
                extra2 = CarExtras("Driver Assist Pack", "$575")
                car_object.add_extra(extra1)
                car_object.add_extra(extra2)
                
                # 添加到车系
                car_series.add_car_object(car_object)
            
            print(f"✅ 成功创建 {car_series.get_car_objects_count()} 个CarObject实例")
            
        except Exception as e:
            print(f"❌ 创建CarObject实例失败: {e}")

    # === 移除的UI抓取方法 ===
    # 以下方法已移除，因为不再需要UI交互：
    # - get_visible_sub_models() 
    # - get_key_features_robust()
    # - extract_key_features_comprehensive()
    # - _extract_key_features_from_ui()
    # - robust_click_button()
    # - get_pagination_info()
    # - parse_pagination_info()
    # - scroll_carousel()
    # - 所有悬停、点击、滚动相关的复杂逻辑
    
    def __legacy_ui_methods_removed(self):
        """
        已移除的UI抓取方法列表：
        - 所有与页面元素交互的方法（点击、悬停、滚动）
        - 分页处理逻辑
        - DOM元素查找和解析
        - 轮播导航逻辑
        - 模态框处理
        - View Specifications按钮点击
        
        现在只使用Ford API直接获取完整数据，大大简化了代码复杂度。
        """
        pass
